<?php

namespace Anchu\Cockpit\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Lvzmen\Helper\iFormatHelper;

class XcdnController extends Controller
{
    const USERINFO_URL = 'https://szsn.zjagri.cn/gateway/oauth2/userinfo';
    const TOKEN_URL = 'https://szsn.zjagri.cn/gateway/oauth2/token';

    private $appKey;
    private $appSecret;
    private $expired;

    public function __construct()
    {
        $this->appKey = env('XCDN_APP_KEY', '');
        $this->appSecret = env('XCDN_APP_SECRET', '');
        $this->expired = env('XCDN_LOGIN_EXPIRED', 3600);
    }

    /**
     * 工作台登录
     * @return array|string
     */
    public function login()
    {
        $code = request()->query('code', '');
        $result = $this->getUserInfo($code);
        if (!isset($result['data']['accountId'])) {
            $_SERVER['xcdn.login.result'] = json_encode($result);
            return $this->fail('鉴权失败', 401);
        }

        // 对用户名或者手机号做签名
        $timestamp = time();
        $sign = md5('login:' . $result['data']['accountId'] . ':' . $result['data']['unionid'] . ':' . $timestamp);

        Cache::put($sign, [
            'operatorId' => $result['data']['accountId'],
            'mobile' => $result['data']['unionid'],
            'timestamp' => $timestamp,
        ], $this->expired);
        return $this->success([
            'token' => $sign,
            'expired' => $this->expired,
        ]);
    }

    /**
     * 获取用户信息
     * @param string $code
     * @return bool|string
     */
    public function getUserInfo($code = '')
    {
        list($accessToken,) = $this->getAccessToken($code);
        $httpParams = [
            'access_token' => $accessToken
        ];
        return $this->curl(self::USERINFO_URL, $httpParams);
    }

    /**
     * 工作台登录，获取access_token
     * @return mixed|string
     */
    protected function getAccessToken($code = '')
    {
        $httpParams = [
            'grant_type' => 'authorization_code',
            'client_id' => $this->appKey,
            'client_secret' => $this->appSecret,
            'code' => $code,
        ];
        $res = $this->curl(self::TOKEN_URL, $httpParams);
        if (!isset($res['code']) || $res['code'] != 200) {
            throw new \Exception($res['message'] ?? '获取accessToken失败');
        }
        $data = $res['data'] ?? [];
        $accessToken = $data['access_token'];
        $refreshToken = $data['refresh_token'];
        return [$accessToken, $refreshToken];
    }

    /**
     * 工具，此处使用
     * @param $url
     * @return bool|string
     */
    private function curl($url, $params = [], $method = 'GET')
    {
        try {
            $ch = curl_init();
            if ($method == 'GET') {
                $paramsList = [];
                foreach ($params as $key => $value) {
                    $paramsList[] = $key . '=' . $value;
                }
                $url = $url . '?' . implode('&', $paramsList);
                curl_setopt($ch, CURLOPT_POST, false);
            }

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // 取消结果自动打印
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $res = curl_exec($ch);
            curl_close($ch);
            return json_decode($res, 1);
        } catch (\Exception $e) {
            exit($e->getMessage());
        }
    }

    protected function success($data, string $message = 'success')
    {
        $responseData = [
            'code' => 0,
            'msg' => $message,
        ];
        if (!empty($data)) {
            $responseData['data'] = $data;
        } else {
            $responseData['data'] = [];
        }
        return response()->json($responseData);
    }

    protected function fail(string $message = 'error', $code = -1)
    {
        $responseData = [
            'code' => $code,
            'msg' => $message,
        ];
        return response()->json($responseData);
    }
}
